import { Form, message, Modal, Radio } from 'antd';
import React from 'react';
import { useBoolean, useRequest } from 'ahooks';
import { GlobalFormLayout } from '@/layouts/Form';
import request from '@/utils/request';
import ProcessForm from '../ProcessForm';

function VersionCopyModal({ data, visible, onCancel, form }) {
  const { getFieldDecorator, getFieldValue, validateFields } = form;
  const { processId, versionId } = data;
  const [submitting, { setTrue: onSubmitting, setFalse: finishSubmit }] = useBoolean(false);

  const { data: processInfo, loading } = useRequest(() =>
    request.get(`/process/getProcess?processId=${processId}`)
  );

  const copyType = getFieldValue('copyType');

  const handleSubmit = () => {
    validateFields((err, data) => {
      if (!err) {
        onSubmitting();
        if (data.copyType === 'newVersion') {
          request
            .post(`/process/copyVersion?processId=${processId}&versionId=${versionId}`)
            .then(() => {
              message.success('新建版本成功');
              onCancel();
            })
            .finally(() => finishSubmit());
        } else {
          request
            .post('/process/createProcess', {
              data: {
                ...data,
                basedOnProcessId: processId,
                basedOnVersionId: versionId,
                onlyProcessGraph: true,
              },
            })
            .then(() => {
              message.success('新建流程成功');
              onCancel();
            })
            .finally(() => finishSubmit());
        }
      }
    });
  };

  return (
    <Modal
      title="复制版本"
      visible={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={submitting}
    >
      <Form {...GlobalFormLayout}>
        <Form.Item label="复制类型" required>
          {getFieldDecorator('copyType', {
            initialValue: 'newVersion',
          })(
            <Radio.Group>
              <Radio key="newVersion" value="newVersion">
                新建版本
              </Radio>
              <Radio key="newProcess" value="newProcess">
                新建流程
              </Radio>
            </Radio.Group>
          )}
        </Form.Item>
        {copyType === 'newProcess' && !loading && (
          <ProcessForm form={form} {...processInfo} isEdit={false} />
        )}
      </Form>
    </Modal>
  );
}

export default Form.create()(VersionCopyModal);
